package com.example.questionsystem.modules.qu.util;

import com.example.questionsystem.modules.qu.entity.SubjectSessions;
import com.example.questionsystem.modules.qu.service.SubjectsService;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.docx4j.Docx4J;
import org.docx4j.convert.out.HTMLSettings;
import org.docx4j.convert.out.html.HTMLConversionImageHandler;
import org.docx4j.convert.out.html.HtmlExporterNG2;
import org.docx4j.model.structure.HeaderFooterPolicy;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
public class WordToHtmlConverter {

    public static String convertWordToHtml(MultipartFile file) throws Exception {

        try (InputStream inputStream = file.getInputStream()) {
            // 1. 加载Word文档
            WordprocessingMLPackage wordPackage = Docx4J.load(inputStream);

            for (SectionWrapper section : wordPackage.getDocumentModel().getSections()) {
                HeaderFooterPolicy policy = section.getHeaderFooterPolicy();

                // 清除默认页眉
                if (policy.getDefaultHeader() != null) {
                    policy.getDefaultHeader().getContent().clear();
                }

                // 清除默认页脚
                if (policy.getDefaultFooter() != null) {
                    policy.getDefaultFooter().getContent().clear();
                }

            }
            // 2. 配置HTML设置
            HTMLSettings htmlSettings = new HTMLSettings();
            htmlSettings.setImageHandler(new ServerImageHandler());
            htmlSettings.setImageDirPath(null);  // 禁用本地保存
            htmlSettings.setImageTargetUri(null); // 禁用相对路径

            // 3. 创建导出器
            HtmlExporterNG2 exporter = new HtmlExporterNG2();

            // 4. 执行转换
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            StreamResult streamResult = new StreamResult(outputStream);
            
            exporter.html(
                wordPackage,
                streamResult,
                htmlSettings
            );

            // 5. 返回HTML内容
            return outputStream.toString(StandardCharsets.UTF_8.name());
        }
    }


    public static class ServerImageHandler extends HTMLConversionImageHandler {

        public static SubjectSessions subjectSessions;

        public ServerImageHandler() {
            super(null, null, false); // 必须调用父类构造
        }

        @Override
        protected String setupImageUri(File imageFile) {
            try {
                // 1. 读取临时图片文件
                byte[] imageBytes = java.nio.file.Files.readAllBytes(imageFile.toPath());
                int i = 0;
                // 2. 获取文件类型
                String contentType = java.nio.file.Files.probeContentType(imageFile.toPath());
                String extension = getFileExtension(contentType);
                // 获取当前时间戳
                String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                String filename = timestamp + extension;

                // 3. 上传到服务器
                String imageUrl = uploadImageToServer(imageBytes, filename);
                System.out.println("[SUCCESS] 图片上传成功，URL: " + imageUrl);
                return imageUrl;

            } catch (Exception e) {
                System.err.println("[ERROR] 图片处理失败: " + e.getMessage());
                return "https://example.com/error.png"; // 错误占位图
            }
        }

        private String getFileExtension(String contentType) {
            if (contentType == null) return ".dat";
            switch (contentType) {
                case "image/png": return ".png";
                case "image/jpeg": return ".jpg";
                case "image/gif": return ".gif";
                case "image/bmp": return ".bmp";
                default: return ".dat";
            }
        }

        private String uploadImageToServer(byte[] imageBytes, String filename) {
            // 配置超时时间（5秒连接，10秒传输）
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setSocketTimeout(10000)
                    .build();

            try (CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(config)
                    .build()) {

                HttpPost uploadFile = new HttpPost("http://localhost:8101/question/uploadImage");
                
                // 构建Multipart请求
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.addBinaryBody(
                    "file",
                    imageBytes,
                    ContentType.APPLICATION_OCTET_STREAM,
                    filename
                );
                
                HttpEntity multipart = builder.build();
                uploadFile.setEntity(multipart);

                // 执行请求
                try (CloseableHttpResponse response = httpClient.execute(uploadFile)) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        String jsonResponse = EntityUtils.toString(response.getEntity());
                        JSONObject json = JSON.parseObject(jsonResponse);
                        return json.getString("data"); // 假设返回格式 {"url": "http://..."}
                    } else {
                        throw new RuntimeException("服务器返回错误状态码: " + statusCode);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("图片上传失败: " + e.getMessage(), e);
            }
        }
    }
}